<template>
	<cl-crud ref="Crud">
		<cl-row>
			<!-- 刷新按钮 -->
			<cl-refresh-btn />
			<!-- 新增按钮 -->
			<cl-add-btn />
			<cl-flex1 />
			<!-- 条件搜索 -->
			<cl-search ref="Search" />
		</cl-row>

		<cl-row>
			<!-- 数据表格 -->
			<cl-table ref="Table">
				<template #slot-qrcode-btn="{ scope }">
					<el-button
						type="info"
						@click="
							() => {
								makeQrcode(scope.row.id);
							}
						"
						>生成二维码 </el-button
					>
				</template>
				<template #slot-invite-btn="{ scope }">
					<el-button
						type="success"
						@click="
							() => {
								showInvitePoster(scope.row);
							}
						"
						>查看海报</el-button
					>
				</template>
			</cl-table>
		</cl-row>

		<cl-row>
			<cl-flex1 />
			<!-- 分页控件 -->
			<cl-pagination />
		</cl-row>

		<!-- 新增、编辑 -->
		<cl-upsert ref="Upsert" />
	</cl-crud>
	<cl-dialog title="邀请海报" v-model="invitePosterDialogVisible" width="400px">
		<div style="text-align: center; display: flex; flex-direction: column; align-items: center">
			<div class="qrcode-container" style="margin: 20px 0">
				<img :src="qrCodeUrl" alt="二维码" style="width: 310px; height: 438px" />
			</div>
			<el-button type="primary" @click="saveInvitePoster">保存海报</el-button>
		</div>
	</cl-dialog>
</template>

<script lang="ts" setup>
defineOptions({
	name: "qrcode-qrcode",
});

import { useCrud, useTable, useUpsert, useSearch } from "@cool-vue/crud";
import { useCool } from "/@/cool";
import { useI18n } from "vue-i18n";
import { reactive, ref } from "vue";
import { useDict } from '/$/dict';
import { ElMessage } from 'element-plus';
import UserSelect from "/$/user/components/user-select.vue";
import { useBase } from '/$/base';

const { service } = useCool();
const { t } = useI18n();
const { dict } = useDict();
const { user } = useBase();

// 选项
const options = reactive({
	status: [
		{ label: t("禁用"), value: 0, type: "danger" },
		{ label: t("启用"), value: 1, type: "success" },
	],
	type: [
		{ label: t("普通"), value: 0, type: "danger" },
		{ label: t("推广"), value: 1, type: "success" },
	],
});

// cl-upsert
const Upsert = useUpsert({
	items: [
		{
			label: t("名称"),
			prop: "daren",
			component: { name: "el-input", props: { clearable: true } },
			span: 12,
			required: true,
		},
		{
			label: t('选择渠道'),
			prop: 'channelId',
			component: {
				name: 'el-select',
				options: dict.get('Channel')
			},
			span: 8
		},
	],
});

// cl-table
const Table = useTable({
	columns: [
		// id
		{
			label: t('ID'),
			prop: 'id',
			minWidth: 100
		},
		// 达人名称
		{
			label: t('达人名称'),
			prop: 'daren',
			minWidth: 100
		},
		{
			label: t('渠道'),
			prop: 'channelId',
			formatter: (row, column, cellValue) => {
				const val = dict.get('Channel').value.find(item => item.value === cellValue);
				return val ? val.label : cellValue;
			},
			minWidth: 100
		},
		{
			label: t("小程序二维码"),
			prop: "qrcodeUrl",
			minWidth: 100,
			component: { name: "cl-image", props: { size: 60 } },
		},
		{
			type: 'op',
			buttons: ['edit', 'slot-invite-btn', 'slot-qrcode-btn'],
			width: 400
		}
	],
});

// cl-search
const Search = useSearch();

// cl-crud
const Crud = useCrud(
	{
		service: service.qrcode.qrcode,
		async onRefresh(params, { next, done, render }) {
			params.adminId = user.info?.id;
            const { list } = await next(params);
            // 渲染数据
			render(list);
        }
	},
	(app) => {
		app.refresh();
	},
);

// 刷新
function refresh(params?: any) {
	Crud.value?.refresh(params);
}

// 生成二维码
function makeQrcode(id: number) {
	service.qrcode.qrcode.makeQrcode({ id: id }).then((res) => {
		console.log(res)
	});
}

// 添加邀请海报相关的响应式变量
const invitePosterDialogVisible = ref(false);
const qrCodeUrl = ref('');

function saveInvitePoster() {
	const link = document.createElement('a');
	link.download = `邀请海报_${new Date().getTime()}.png`;
	link.href = qrCodeUrl.value;
	document.body.appendChild(link);
	link.click();
	document.body.removeChild(link);
	ElMessage({
		type: 'success',
		message: '海报已保存'
	});
}

async function showInvitePoster(row: any) {
	// 创建 Canvas
	const canvas = document.createElement('canvas');
	const ctx = canvas.getContext('2d');

	// 设置画布大小为固定比例
	canvas.width = 2480;
	canvas.height = 3508;

	const bgImage = new Image();
	bgImage.crossOrigin = 'anonymous';
	bgImage.src =
		'https://tongrenlijiaojing.oss-cn-beijing.aliyuncs.com/wechat/cityPoster/wuhan_poster.jpg';

	await new Promise((resolve, reject) => {
		bgImage.onload = resolve;
		bgImage.onerror = reject;
	});

	// 计算背景图绘制参数，保持比例
	const scale = Math.max(canvas.width / bgImage.width, canvas.height / bgImage.height);
	const x = (canvas.width - bgImage.width * scale) / 2;
	const y = (canvas.height - bgImage.height * scale) / 2;

	// 绘制背景图（自适应）
	ctx.drawImage(bgImage, x, y, bgImage.width * scale, bgImage.height * scale);



	const qrcodeImage = new Image();
	qrcodeImage.crossOrigin = 'anonymous';
	const newUrl = row.qrcodeUrl.replace('http://', 'https://');
	qrcodeImage.src = newUrl;
	await new Promise((resolve, reject) => {
		qrcodeImage.onload = resolve;
		qrcodeImage.onerror = reject;
	});
	// 绘制二维码
	ctx.drawImage(qrcodeImage, 1900, 2715, 440, 440);

	// 在左下角添加二维码ID
	ctx.fillStyle = '#000000'; // 设置文本颜色为黑色
	ctx.font = '60px Arial'; // 设置字体大小和类型
	ctx.textAlign = 'left'; // 设置文本对齐方式
	ctx.fillText(`${row.id}`, 100, canvas.height - 100); // 在左下角绘制ID文本

	// 将合成后的图片转换为 base64
	qrCodeUrl.value = canvas.toDataURL('image/png');
	// 显示合并后的图片
	invitePosterDialogVisible.value = true;
}
</script>
